package com.sample.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.provider.Settings;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

@SuppressLint("DefaultLocale") public class Tools {
	private static Toast TOAST = null;
	public Tools() {
		
	}
	public static boolean CheckSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			return true;
		else
			return false;
	}
	@SuppressLint("ShowToast") public static void showTextToast(Context context,String msg) {
	    if (TOAST == null) {
	    	TOAST = Toast.makeText(context, msg, 2);
	    } else {
	    	TOAST.setText(msg);
	    }
	    TOAST.show();
	}
	/**
	 * File转为byte[]
	 * 
	 * @param f
	 * @return
	 */
	public static byte[] file2Byte(File f) {
		if (f == null) {
			return null;
		}
		try {
			FileInputStream stream = new FileInputStream(f);
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			byte[] b = new byte[1024];
			int n;
			while ((n = stream.read(b)) != -1) {
				out.write(b, 0, n);
			}
			stream.close();
			out.close();
			return out.toByteArray();
		} catch (IOException e) {
		}
		return null;
	}
	
	/**
	 * Bitmap转为byte[]
	 * 
	 * @param bm
	 * @return
	 */
	public static byte[] bitmap2Bytes(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
		return baos.toByteArray();
	}

	 public static Bitmap getBitmap(Context con, String path) {
			if (path.toLowerCase().startsWith("http")) {
				return getHttpBitmap(path);
			} else {
				return getAssetsBitmap(con, path);
			}
	}

	public static Bitmap getFileBitmap(Context con, String name) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeFile(name);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	public static Bitmap getAssetsBitmap(Context con, String path) {
		Bitmap image = null;
		try {
			AssetManager am = con.getResources().getAssets();
			try {
				InputStream is = am.open(path);
				image = BitmapFactory.decodeStream(is);
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}

	public static Bitmap getHttpBitmap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setConnectTimeout(0);
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (bitmap != null) {
		}
		return bitmap;
	}

	public static String saveBitmapToFile(String savepath, Bitmap bmp,
			String http) {
		if (folderCreate(savepath)) {
			String imgname = System.currentTimeMillis() + ".t";
			String filename = savepath + imgname;
			if (fileCreate(savepath, imgname) != null) {
				try {
					FileOutputStream out = new FileOutputStream(filename);
					bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return imgname;
			}
		}
		return null;
	}

	public static boolean saveBitmapToFile(String filepath, String filename,
			CompressFormat format, Bitmap bmp) {
		if (folderCreate(filepath)) {
			if (fileCreate(filepath, filename) != null) {
				try {
					FileOutputStream out = new FileOutputStream(filepath
							+ filename);
					bmp.compress(format, 90, out);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}
		}
		return false;
	}

	public static boolean delFolder(String folderpath, String onlyFirst) {
		File folder = new File(folderpath);
		if (!folder.exists()) {
			return false;
		}
		if (!folder.isDirectory()) {
			return false;
		}
		File[] files = folder.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (onlyFirst == null
						|| files[i].getName().indexOf(onlyFirst) == 0) {
					files[i].delete();
				}
			}
		}
		return true;
	}
	/**
	 * 文件是否存在
	 * 
	 * @param filepath
	 *            文件路径
	 * @param filename
	 *            文件名
	 */
	public static boolean fileExists(String filepath, String filename) {
		File file = new File(filepath + filename);
		return file.exists();
	}

	/**
	 * 创建文件夹
	 * 
	 * @param filepath
	 * @return
	 */
	public static boolean folderCreate_(String filepath) {
		File folder = new File(filepath);
		if (!folder.exists()) {
			try {
				boolean b = folder.mkdirs();
				return b;
			} catch (Exception e) {
				return false;
			}
		}
		return true;
	}

	public static boolean folderCreate(String filePath) {
		try {
			File file = null;
			String newPath = null;
			String[] path = filePath.split("/");
			for (int i = 0; i < path.length; i++) {
				if (newPath == null) {
					newPath = path[i];
				} else {
					newPath = newPath + "/" + path[i];
				}
				file = new File(newPath);
				if (!file.exists()) {
					file.mkdir();
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 创建文件
	 * 
	 * @param filepath
	 *            文件路径
	 * @param filename
	 *            文件名
	 * @return
	 */
	public static File fileCreate(String filepath, String filename) {
		try {
			File file = new File(filepath + filename);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			return file;
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean fileRename(String filepath, String filename,
			String newname) {
		try {
			File file = new File(filepath + filename);
			String path = file.getParent();
			File newfile = new File(path + newname);
			if (file.exists()) {
				return file.renameTo(newfile);
			}
		} catch (Exception e) {
		}
		return false;
	}
	public static boolean writeFile(String filepath, String filename,
			byte[] info) {
		File file = fileCreate(filepath, filename);

		try {
			FileOutputStream op = new FileOutputStream(file);
			op.write(info);
			op.flush();
			op.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}
	/**
	 * 版本号
	 * @param con
	 * @return
	 */
	public static int getAppVersionCode(Context con) {
		try {
			PackageInfo pkgInfo = con.getPackageManager().getPackageInfo(
					con.getPackageName(), 0);
			if (pkgInfo != null) {
				return pkgInfo.versionCode;
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return -1;
	}
	/**
	 * 版本名称
	 * @param con
	 * @return
	 */
	public static String getAppVersionName(Context con) {
		try {
			PackageInfo pkgInfo = con.getPackageManager().getPackageInfo(
					con.getPackageName(), 0);
			if (pkgInfo != null) {
				return pkgInfo.versionName;
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 手机号码判断
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles){  
		Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");  
		Matcher m = p.matcher(mobiles);  
		System.out.println(m.matches()+"---");  
		return m.matches(); 
	}
	/**
	 * 固定电话判断
	 * @param telephone
	 * @return
	 */
	public static boolean isTelephoneNum(String telephone){
		Pattern p = Pattern.compile("^[\\d|\\D]{0,}\\d{7,11}[\\d|\\D]{0,}$");  
		Matcher m = p.matcher(telephone);  
		System.out.println(m.matches()+"---");  
		return m.matches(); 
	}
	/**
	 * 隐藏软键盘
	 * @param activity
	 */
	public static void hideInputMethod(Activity activity) {
		if (null == activity) {
			return;
			}
		if (null != activity.getCurrentFocus() && null != activity.getCurrentFocus().getWindowToken()){
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	/** 
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
	 */  
	public static int dip2px(Context context, float dpValue) {  
		final float scale = context.getResources().getDisplayMetrics().density;  
		return (int) (dpValue * scale + 0.5f);  
	}  

	/** 
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
	 */  
	public static int px2dip(Context context, float pxValue) {  
		final float scale = context.getResources().getDisplayMetrics().density;  
		return (int) (pxValue / scale + 0.5f);  
	}  
	public static boolean isLocationServiceOpen(Context context){
		LocationManager locationManager  
		= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快） 
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
		// 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位） 
		boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
		if (gps || network) { 
			return true;
		} 
		return false; 
	}
	public static void openGPS(Context context) { 
		 Intent intent =  new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
		 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(intent);
	}
}
